<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/6
 * Time: 14:40
 */
namespace App\Http\Controllers\Api\LandingC;

use App\Http\Controllers\Controller;
use App\Repositories\CollectMoneyBillRepository;
use App\Repositories\PersonalAccountWithdrawRepository;
use App\Repositories\RepaymentAccountWithdrawRepository;
use App\Repositories\RepaymentPlanConsumeRepository;
use App\Repositories\RepaymentPlanFailHandlersRepository;
use App\Repositories\RepaymentPlanRepository;
use App\Repositories\ThreeApiErrorLogsRepository;
use App\Repositories\UserCreditCardRepository;
use App\Repositories\UserPassageRegisterRepository;
use App\Repositories\UserRepository;
use App\Services\CollectMoneyProfitService;
use App\Services\MessageService;
use App\Services\RepaymentProfitService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LandingCNotifyController extends Controller
{
    protected $threeApiErrorLogsRepository;
    protected $repaymentProfitService;
    protected $repaymentAccountWithdrawRepository;
    protected $personalAccountWithdrawRepository;
    protected $collectMoneyProfitService;
    protected $userRepository;
    protected $userCreditCardRepository;
    protected $repaymentPlanFailHandlersRepository;
    protected $messageService;

    public function __construct(ThreeApiErrorLogsRepository $threeApiErrorLogsRepository,
                                RepaymentProfitService $repaymentProfitService,
                                RepaymentAccountWithdrawRepository $repaymentAccountWithdrawRepository,
                                PersonalAccountWithdrawRepository $personalAccountWithdrawRepository,
                                CollectMoneyProfitService $collectMoneyProfitService,
                                UserRepository $userRepository,
                                UserCreditCardRepository $userCreditCardRepository,
                                RepaymentPlanFailHandlersRepository $repaymentPlanFailHandlersRepository,
                                MessageService $messageService)
    {
        $this->threeApiErrorLogsRepository = $threeApiErrorLogsRepository;
        $this->repaymentProfitService = $repaymentProfitService;
        $this->repaymentAccountWithdrawRepository = $repaymentAccountWithdrawRepository;
        $this->personalAccountWithdrawRepository = $personalAccountWithdrawRepository;
        $this->collectMoneyProfitService = $collectMoneyProfitService;
        $this->userRepository = $userRepository;
        $this->userCreditCardRepository = $userCreditCardRepository;
        $this->repaymentPlanFailHandlersRepository = $repaymentPlanFailHandlersRepository;
        $this->messageService = $messageService;
    }
    /**
     * 注册子商户号回调
     */
    public function subMechantRegisterNotify(Request $request)
    {
        echo 'SUCCESS';
        Log::info('subMechantRegisterNotifyC:' . json_encode($request->all()));
    }

    /**
     * 子商户开卡成功返回url
     *  subMechantOpenCardReturn:{"code":"SUCCESS","message":"\u00e5\u00bc\u0080\u00e5\u008d\u00a1\u00e6\u0088\u0090\u00e5\u008a\u009f","messageEncode":"5byA5Y2h5oiQ5Yqf","dsorderid":"A911725397331840"}
     */
    public function subMechantOpenCardReturn(Request $request)
    {
        Log::info('subMechantOpenCardReturnC:' . json_encode($request->all()));
        $userPassageRegisterRepository = new UserPassageRegisterRepository();
        //更新开卡状态
        if ($request->code == 'SUCCESS') {
            $isOpen = $userPassageRegisterRepository->orderNoByStatus($request->dsorderid);
            echo 'SUCCESS';
        }
        //如果是未开通
        if (!empty($isOpen) && 0 == $isOpen->is_open) {
            $userPassageRegisterRepository->updateOpenCardStatus($request->dsorderid, 2);//开通中
            $errorData = [
                'order_no' => $request->dsorderid,
                'error_code' => $request->code,
                'error_msg' => json_encode($request->all()),
                'api_type' => 3
            ];
            $this->threeApiErrorLogsRepository->create($errorData);
        }
    }

    /**
     * 子商户开卡回调
     * subMechantOpenCardNotify:{"sign":"c49eb6085109a81c4ff26c9ef283369f","message":"\u6210\u529f:null","cardNo":"6225768649617527","dsorderid":"A911730952304802","code":"SUCCESS","mobile":"13926001684"}
     */
    public function subMechantOpenCardNotify(Request $request)
    {
        Log::info('subMechantOpenCardNotifyC:' . json_encode($request->all()));
        $userPassageRegisterRepository = new UserPassageRegisterRepository();
        //更新开卡状态
        if ($request->code == 'SUCCESS') {
            $userPassageRegisterRepository->updateOpenCardStatus($request->dsorderid, 1);
            echo 'SUCCESS';
        } else {
            $userPassageRegisterRepository->updateOpenCardStatus($request->dsorderid, 0);
        }
        $errorData = [
            'order_no' => $request->dsorderid,
            'error_code' => $request->code,
            'error_msg' => json_encode($request->all()),
            'api_type' => 3
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
    }

    /**
     * 消费回调
     * {
     * "sign": "7aca35d53b14e4e4af07fa984cc09181",
     * "message": "支付成功",
     * "amount": "20.00",
     * "dsorderid": "A821456714614513",
     * "subMerBalance": "23.06",
     * "code": "SUCCESS"
     * }
     *  {"sign":"7aca35d53b14e4e4af07fa984cc09181","message":"\u652f\u4ed8\u6210\u529f","amount":"20.00","dsorderid":"A821456714614513","subMerBalance":"23.06","code":"SUCCESS"}
     */
    public function consumeNotify(Request $request)
    {
        Log::info('consumeNotifyC:' . json_encode($request->all()));
        $repaymentPlanConsumeRepository = new RepaymentPlanConsumeRepository();
        $consume = $repaymentPlanConsumeRepository->byConsumeSn($request->dsorderid);
        $repaymentPlan = new RepaymentPlanRepository();
        $plan = $repaymentPlan->byId($consume->repayment_plan_id);
        //更新消费状态
        if ($request->code == 'SUCCESS') {
            echo 'SUCCESS';
            $repaymentPlanConsumeRepository->updateStatusByConsumeSn($request->dsorderid, 2002);//成功
            //发送消费成功消息提醒
            $userOwn = $this->userRepository->byId($plan->user_id);
            $creditCard = $this->userCreditCardRepository->isExistUserBankNo($plan->user_id, $consume->bank_no);
            $this->messageService->messageTemplate(17, $userOwn->invited_code, $creditCard->bank_no, $creditCard->bank_description,
                $consume->consume_money, '', '', $consume->repayment_plan_id, '', '');
            $this->repaymentProfitService->profit($request->dsorderid, $consume->consume_money, $consume->consume_service_charge,
                $consume->consume_passage_id, $plan->user_id, $creditCard->bank_code, $userOwn->mobile);
        } else {
            $message = isset($request->message) ? $request->message : '';
            $repaymentPlanConsumeRepository->updateStatusByConsumeSn($request->dsorderid, 2003, $message);//失败
            if (date('Y-m-d') == date('Y-m-d', $consume->consume_time)) {
                $plan->update(['repayment_plan_status' => 1005, 'update_plan_time' => time()]);
            }
            //发送消费失败消息提醒
            $userOwn = $this->userRepository->byId($plan->user_id);
            $creditCard = $this->userCreditCardRepository->isExistUserBankNo($plan->user_id, $consume->bank_no);
            $this->messageService->messageTemplate(16, $userOwn->invited_code, $creditCard->bank_no, $creditCard->bank_description,
                $consume->consume_money, '', '', $consume->repayment_plan_id, '', '');
        }
        $errorData = [
            'order_no' => $request->dsorderid,
            'error_code' => $request->code,
            'error_msg' => json_encode($request->all()),
            'api_type' => 5
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
    }

    /**
     * 还款回调
     */
    public function repaymentNotify(Request $request)
    {
        Log::info('repaymentNotifyC:' . json_encode($request->all()));
        $this->repaymentProfitService->repaymentC($request);
    }

    /**
     * 提现回调
     */
    public function withdrawNotify(Request $request)
    {
        Log::info('withdrawNotifyC:' . json_encode($request->all()));
        $withdraw = $this->repaymentAccountWithdrawRepository->byWithdrawNo($request->dsorderid);
        //更新还款提现状态
        if ($request->code == 'SUCCESS') {
            $this->repaymentAccountWithdrawRepository->updateStatusByWithdrawNo($request->dsorderid, 4002);//成功
            echo 'SUCCESS';
            //提现成功失败消息提醒
            $userOwn = $this->userRepository->byId($withdraw->user_id);
            $this->messageService->messageTemplate(18, $userOwn->invited_code, $withdraw->bank_no, $withdraw->bank_description,
                $withdraw->withdraw_money, '', '', 0, '', '');
        } else {
            $this->repaymentAccountWithdrawRepository->updateStatusByWithdrawNo($request->dsorderid, 4003);//失败
            $data['withdraw_status'] = 4003;
            $data['fail_message'] = $request->errtext;
            Log::info('自动处理进入手动处理');
            $creditCard = $this->userCreditCardRepository->byId($withdraw->credit_card_id);
            //自动处理进入手动处理
            $data = [
                'fail_repayment_sn' => $withdraw->withdraw_no,
                'repayment_plan_id' => $withdraw->repayment_plan_id,
                'plan_repayment_id' => $withdraw->plan_repayment_id,
                'user_id' => $withdraw->user_id,
                'credit_card_id' => $withdraw->credit_card_id,
                'repayment_passage_id' => $withdraw->passage_id,
                'repayment_money' => $withdraw->withdraw_money,
                'sub_merchant_no' => $withdraw->sub_merchant_no,
                'bank_no' => $withdraw->bank_no,
                'bank_mobile' => $creditCard->bank_mobile,
                'api_result' => json_encode($request->all()),
                'create_time' => time(),
            ];
            $this->repaymentPlanFailHandlersRepository->create($data);
        }
        $errorData = [
            'order_no' => $request->dsorderid,
            'error_code' => $request->code,
            'error_msg' => json_encode($request->all()),
            'api_type' => 10
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
    }

    /**
     * 收银跳转url
     */
    public function quickMoneyReturn(Request $request)
    {
        Log::info('quickMoneyReturnC:' . json_encode($request->all()));
        $userPassageRegisterRepository = new CollectMoneyBillRepository();
        //如果是未支付
        $isSuccess = $userPassageRegisterRepository->findByBillSn($request->orderNo);
        if (!empty($isSuccess) && 6000 == $isSuccess->collect_money_status) {
            $userPassageRegisterRepository->updateBillStatus($request->orderNo, 6001);//处理中
            $errorData = [
                'order_no' => $request->orderNo,
                'error_code' => 6001,
                'error_msg' => '交易处理中',
                'api_type' => 21
            ];
            $this->threeApiErrorLogsRepository->create($errorData);
        }
    }
    
    /**
     * 收银回调
     * {"sign":"d3f2772568c19279d9a0de012e480848","amount":"10.00","transtype":"18","merchno":"lmkj25se267f69f","status":"00",
     * "signType":"MD5","dsorderid":"A913257061602895","orderid":"2018091315580100100122589","paytime":"20180913155846"}
     */
    public function quickMoneyNotify(Request $request)
    {
        Log::info('quickMoneyNotifyC:' . json_encode($request->all()));
        $errorData = [
            'order_no' => $request->dsorderid,
            'error_code' => $request->status,
            'error_msg' => json_encode($request->all()),
            'api_type' => 22
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
        $this->collectMoneyProfitService->quickMoneyNotify($request);
    }
}